package com.ruoyi.market.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.market.domain.Project;
import com.ruoyi.market.domain.TreeProject;
import com.ruoyi.market.mapper.ProjectMapper;
import com.ruoyi.market.service.IProjectService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务项目 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class ProjectServiceImpl implements IProjectService
{
    private static final Logger log = LoggerFactory.getLogger(ProjectServiceImpl.class);

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    protected Validator validator;

    /**
     * 根据条件分页查询服务项目列表
     * 
     * @param project 服务项目信息
     * @return 服务项目信息集合信息
     */
    @Override
    public List<Project> selectProjectList(Project project)
    {
        return projectMapper.selectProjectList(project);
    }

    /**
     * 查询服务项目树结构信息
     *
     * @param project 服务项目信息
     * @return 服务项目树信息集合
     */
    @Override
    public List<TreeProject> selectProjectTreeList(Project project)
    {
        List<Project> projects = SpringUtils.getAopProxy(this).selectProjectList(project);
        return buildProjectTreeSelect(projects);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param projects 服务项目信息
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeProject> buildProjectTreeSelect(List<Project> projects)
    {
        List<Project> projectTrees = buildProjectTree(projects);
        return projectTrees.stream().map(TreeProject::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param projects 服务项目信息
     * @return 树结构列表
     */
    @Override
    public List<Project> buildProjectTree(List<Project> projects)
    {
        List<Project> returnList = new ArrayList<Project>();
        List<Long> tempList = projects.stream().map(Project::getProjectId).collect(Collectors.toList());
        for (Project project : projects)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(project.getParentId()))
            {
                recursionFn(projects, project);
                returnList.add(project);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = projects;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<Project> list, Project t)
    {
        // 得到子节点列表
        List<Project> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Project tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<Project> getChildList(List<Project> list, Project t)
    {
        List<Project> tlist = new ArrayList<Project>();
        Iterator<Project> it = list.iterator();
        while (it.hasNext())
        {
            Project n = (Project) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getProjectId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<Project> list, Project t)
    {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 通过服务项目名查询服务项目
     * 
     * @param projectTitle 服务项目名
     * @return 服务项目对象信息
     */
    @Override
    public Project selectProjectByProjectTitle(String projectTitle)
    {
        return projectMapper.selectProjectByProjectTitle(projectTitle);
    }

    /**
     * 通过服务项目ID查询服务项目
     * 
     * @param projectId 服务项目ID
     * @return 服务项目对象信息
     */
    @Override
    public Project selectProjectById(Long projectId)
    {
        return projectMapper.selectProjectById(projectId);
    }


    /**
     * 校验名称是否唯一
     *
     * @param project 服务项目
     * @return 结果
     */
    @Override
    public boolean checkProjectTitleUnique(Project project)
    {
        Long projectId = StringUtils.isNull(project.getProjectId()) ? -1L : project.getProjectId();
        Project info = projectMapper.checkProjectTitleUnique(project.getProjectTitle(), project.getShopId());
        if (StringUtils.isNotNull(info) && info.getProjectId().longValue() != projectId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存服务项目信息
     * 
     * @param project 服务项目信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertProject(Project project)
    {
        // 新增服务项目信息
        int rows = projectMapper.insertProject(project);
        return rows;
    }

    /**
     * 修改保存服务项目信息
     * 
     * @param project 服务项目信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateProject(Project project)
    {
        return projectMapper.updateProject(project);
    }

    /**
     * 修改服务项目状态
     * 
     * @param project 服务项目信息
     * @return 结果
     */
    @Override
    public int updateProjectStatus(Project project)
    {
        return projectMapper.updateProject(project);
    }

    /**
     * 随机单是否可用
     *
     * @param project 服务项目信息
     * @return 结果
     */
    @Override
    public int updateProjectIsAble(Project project)
    {
        return projectMapper.updateProject(project);
    }

    /**
     * 批量删除服务项目信息
     * 
     * @param projectIds 需要删除的服务项目ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteProjectByIds(Long[] projectIds) { return projectMapper.deleteProjectByIds(projectIds); }

    /**
     * 导入服务项目数据
     * 
     * @param projectList 服务项目数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作服务项目
     * @return 结果
     */
    @Override
    public String importProject(List<Project> projectList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(projectList) || projectList.size() == 0)
        {
            throw new ServiceException("导入服务项目数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Project project : projectList)
        {
            try
            {
                // 验证是否存在这个服务项目
                Project u = projectMapper.checkProjectUnique(project);
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, project);
                    project.setCreateBy(operName);
                    projectMapper.insertProject(project);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、服务项目 " + project.getProjectTitle() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, project);
                    project.setProjectId(u.getProjectId());
                    project.setUpdateBy(operName);
                    projectMapper.updateProject(project);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、服务项目 " + project.getProjectTitle() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、服务项目 " + project.getProjectTitle() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、服务项目 " + project.getProjectTitle() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
